package controller;

import model.CommentModel;
import model.PostModel;
import view.PostView;

import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;

public class Post {

    public PostModel model;
    public PostView view;

    public Post(PostModel model) {
        this.model = model;
        this.view = new PostView(model);
        this.view.commentField.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent arg0) { }
            public void keyReleased(KeyEvent arg0) {
                // submit on enter, but not if shift is pressed or if text is empty
                if (!arg0.isShiftDown() && arg0.getKeyCode() == KeyEvent.VK_ENTER && view.commentField.getText().trim().length() > 0) {
                    addNewComment();
                }
            }
            public void keyTyped(KeyEvent arg0) { }
        });

        if (model.authorId.compareTo(App.getCurrentUser().userId) == 0)  {
            addContextMenu();
        }
    }

    public void addContextMenu() {
        JPopupMenu popup = new JPopupMenu();

        JMenuItem remove = new JMenuItem("Remove Post");
        remove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                model.remove();
                JComponent parent = (JComponent) view.getParent();
                parent.remove(view);
                parent.revalidate();
            }
        });

        popup.add(remove);

        this.view.setComponentPopupMenu(popup);

    }

    public void addNewComment() {

        // create new comment object
        CommentModel cm = new CommentModel();
        cm.text = this.view.commentField.getText();
        cm.authorName = App.getCurrentUser().name;
        cm.authorId = App.getCurrentUser().userId;
        cm.targetId = this.model.postId;
        cm.date = new Date();
        Comment c = new Comment(cm);

        // sync post model
        this.model.comments.add(c);

        cm.commit();

        // sync post view
        this.view.appendComment(c);

        // clear text
        this.view.commentField.setText("");
    }

}
